package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.yupi.yupicturebackend.Exception.BusinessException;
import com.yupi.yupicturebackend.Exception.ErrorCode;
import com.yupi.yupicturebackend.Exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUploadImpl extends PictureUploadTemplate {
    private static final long ONE_MB = 1024 * 1024;

    @Override
    protected void isPictureValid(Object inputSource) {
        String fileUrl = (String) inputSource;


        // todo
        fileUrl = processUploadPath(fileUrl);
        fileUrl = decodeUploadPath(fileUrl);

        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件url不能为空！");
        // 1. url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件url格式错误！");
        }
        // 2.验证url协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "文件url协议错误！");
        // 3. 发送head请求验证文件是否存在。（有的文件可能不支持head请求下载）
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 未正常返回，无需判断
            if (response.getStatus() != HttpStatus.HTTP_OK){
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)){
                // 允许的文件类型
                final List<String> suffixList = Arrays.asList
                        ("/image/jpg", "/image/jpeg", "/image/png", "/image/gif", "/image/bmp", "/image/webp");
                ThrowUtils.throwIf(!suffixList.contains(contentType), ErrorCode.PARAMS_ERROR, "文件类型错误！！！");
            }
            // 5. 校验文件大小
            String contentLength = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLength)){
                try {
                    long size = Long.parseLong(contentLength);
                    ThrowUtils.throwIf(size >3*ONE_MB, ErrorCode.PARAMS_ERROR, "文件过大");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式异常");
                }
            }
        } finally {
            if (response != null ){
                response.close();
            }
        }
    }


    /**
     * 规范化字符串
     * @param inputSource
     * @param file
     * @throws IOException
     */
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, file);
    }

    /**
     * URL解码含百分号编码的字符串
     * @param uploadPath 需要解码的路径
     * @return 解码后的字符串（所有%xx格式都会被转换）
     */
    public static String decodeUploadPath(String uploadPath) {
        try {
            // 关键方法：使用UTF-8编码进行解码
            return URLDecoder.decode(uploadPath, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            // 理论上UTF-8编码必然存在，此处仅为编译通过
            return uploadPath;
        } catch (IllegalArgumentException e) {
            // 遇到无法解码的格式（如 %xx 中xx不是合法十六进制），把 uploadPath 中所有%字符移除
            return uploadPath.replace("%", "");
        }
    }


    @Override
    protected String  getOriginalFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        // URL解码含%编码的字符串
        fileUrl = decodeUploadPath(fileUrl);
        // 从 URL 中提取主文件名 （例 "/a/b/c/", "/a/b/c", "/a/b/c.jpg"中的 c）
        return FileUtil.mainName(fileUrl);
    }

}
